<?php

use Illuminate\Support\Facades\Input;
use Illuminate\Pagination\Paginator;
/**
 * User Controller
 *
 * @author thanhtv6075
 *
 */

class UserController extends \BaseController {

	/**
	 * Display login screen
	 * @return View
	 */
	public function getLogin(){
		if(Auth::check()){
			if(7 == Auth::user()->type){
				return Redirect::intended('/');
			}

		}

		return View::make('user-login', array('pageTitle' => 'Login '));
	}

	/**
	 * Attempt to login
	 * @return Redirect
	 */
	public function postLogin()
	{
		$validation = Validator::make(Input::all(),
				array(
						'user_id' => 'required|min:3',
						'password' => 'required|min:6',
				)
		);

		if ($validation->passes()){
			
			$user = User::where('user_id', Input::get('user_id'))->first();
			if(!$user){
				$messages = new Illuminate\Support\MessageBag;
				$messages->add('user_id', trans('message.invalid_user_id'));
				return Redirect::to('/user/login')
				->withInput()
				->withErrors($messages);
			}

			if($user->password != Input::get('password')){
				$messages = new Illuminate\Support\MessageBag;
				$messages->add('password', trans('message.invalid_user_password'));
				return Redirect::to('/user/login')
				->withInput()
				->withErrors($messages);
			}

			$credentials = array(
					'user_id' => Input::get('user_id'),
					'password' => Input::get('password'),
					'type' => 7,
			);

			if (Auth::attempt($credentials)){
				return Redirect::intended('/');
			}

			$messages = new Illuminate\Support\MessageBag;
			$messages->add('login_error', trans('message.access_denied'));
			return Redirect::to('/user/login')
			->withInput()
			->withErrors($messages);
		}

		return Redirect::to('/user/login')
		->withInput()
		->withErrors($validation);
	}

	/**
	 * Log a user out
	 * @return Redirect
	 */
	public function getLogout()
	{
		Auth::logout();
		return Redirect::to('/user/login');
	}


	/**
	 * user register
	 * @return View
	 */
	public function getRegister()
	{
		return View::make('user-register', array('pageTitle' => 'Register '));
	}

	/**
	 * user register to db
	 * @return Redirect
	 */
	public function postRegister()
	{
		$input = Input::all();
		$input['hash_password'] = $input['password'];

		$validation = Validator::make($input, User::$rules);

		if ($validation->passes()){
			$input['type'] = 7;
			$input['admin'] = 0;
			User::create($input);
			return Redirect::to('/user/login');
		}

		return Redirect::to('/user/register')
		->withInput()
		->withErrors($validation);
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function showProfile($id)
	{
		if (Session::has('user'))
		{
			$shop = Session::get('user.shop');
			var_dump($shop);
		}
		$users = DB::table('t_user')->paginate(10);;

		return View::make('user-profile', array('users' => $users, 'pageTitle' => 'Profile '));
	}

}
